package com.yuncheng.spcyApi.controller;

import java.io.File;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.URLEncoder;
import java.util.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yuncheng.spcyApi.alog.annotation.Log;
import com.yuncheng.spcyApi.constant.common.BusinessConstant;
import com.yuncheng.spcyApi.constant.common.LogConstant;
import com.yuncheng.spcyApi.constant.common.SpcyConstant;
import com.yuncheng.spcyApi.entity.SpcySqsxBasic;
import com.yuncheng.spcyApi.service.ISpcyLogService;
import com.yuncheng.spcyApi.service.ISpcySqsxBaiscService;
import com.yuncheng.spcyApi.utils.*;
import com.yuncheng.vo.HttpResult;
import com.yuncheng.common.base.controller.BaseController;
import com.yuncheng.spcyApi.entity.SpcyRsGcy;
import com.yuncheng.spcyApi.service.ISpcyRsGcyService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.*;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import utils.LogUtils;
import utils.ObjectToMapUtils;

/**
 * @Description: 审评查验-观察员库
 * @Author: csx
 * @Date: 2023-03-03
 * @Version: V1.0
 */
@Api(tags = "审评查验-观察员库接口")
@RestController
@RequestMapping("/api/spzx-spcy/spcyRsGcy")
public class SpcyRsGcyController extends BaseController<SpcyRsGcy, ISpcyRsGcyService> {

    private static final Logger log = LoggerFactory.getLogger(SpcyRsGcyController.class);

    @Resource
    private ISpcyRsGcyService spcyRsGcyService;

    @Resource
    private LocalFileUploadUtils localFileUploadUtils;

    @Resource
    private MyExcelUtils myExcelUtils;

    @Resource
    private ISpcyLogService spcyLogService;

    @Resource
    private ISpcySqsxBaiscService spcySqsxBaiscService;

    /**
     * 分页列表查询
     *
     * @param spcyRsGcy
     * @param pageNo
     * @param pageSize
     * @return
     */
    @Log(title = "审评查验-观察员库-分页列表查询")
    @ApiOperation(value = "审评查验-观察员库-分页列表查询")
    @GetMapping(value = "/list")
    public HttpResult<?> queryPageList(SpcyRsGcy spcyRsGcy,
                                       @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                       @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        Page<SpcyRsGcy> page = new Page<>(pageNo, pageSize);
        LambdaQueryWrapper<SpcyRsGcy> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.like(StringUtils.isNotEmpty(spcyRsGcy.getFdwmc()),SpcyRsGcy::getFdwmc,spcyRsGcy.getFdwmc());
        queryWrapper.like(StringUtils.isNotEmpty(spcyRsGcy.getFgcyxm()),SpcyRsGcy::getFgcyxm,spcyRsGcy.getFgcyxm());
        queryWrapper.like(StringUtils.isNotEmpty(spcyRsGcy.getFszds()),SpcyRsGcy::getFszds,spcyRsGcy.getFszds());
        queryWrapper.orderByAsc(SpcyRsGcy::getForder);
        queryWrapper.orderByAsc(SpcyRsGcy::getCreateTime);
        Page<SpcyRsGcy> pageList = spcyRsGcyService.page(page, queryWrapper);
        return HttpResult.ok(pageList);
    }



    /**
     * 添加
     *
     * @param spcyRsGcy
     * @return
     */
    @Log(title = "审评查验-观察员库-添加")
    @ApiOperation(value = "审评查验-观察员库-添加")
    @PostMapping(value = "/add")
    public HttpResult<?> add(@RequestBody SpcyRsGcy spcyRsGcy) {
        spcyRsGcyService.save(spcyRsGcy);

        String operContent = "新增信息：";

        // 将map里面的属性和值转String
        Map<String, Object> beanMap = ObjectToMapUtils.objectToMap(spcyRsGcy);
        operContent += LogUtils.MapToStringMethod(beanMap);
        spcyLogService.addLogs(LogConstant.LOGS_RS_GCY,operContent,spcyRsGcy.getId(), LogConstant.LOGS_RS_GCY, SpcyConstant.LOGS_SYS_TYPE_XZ);
        return HttpResult.ok("添加成功");
    }

    /**
     * 编辑
     * @return
     */
    @Log(title = "审评查验-观察员库-编辑")
    @ApiOperation(value = "审评查验-观察员库-编辑")
    @ApiImplicitParam(name = "id",value = "观察员id",required = true)
    @PutMapping(value = "/edit")
    public HttpResult<?> edit(@RequestBody HashMap<String, String> buffer) throws InvocationTargetException, IllegalAccessException {
        if (StringUtils.isEmpty(buffer.get("id"))){
            return HttpResult.error("观察员库id不能为空");
        }
        String gcyId = buffer.get("id");
        SpcyRsGcy oldRsGcy = spcyRsGcyService.getById(gcyId);
        SpcyRsGcy rsGcyUpdate = spcyRsGcyService.getById(gcyId);
        if (rsGcyUpdate == null){
            return HttpResult.error("当前观察员信息数据不存在，请重试");
        }

        ConvertUtils.register(new DateConvert(), java.util.Date.class);
        // 自动完成页面到bean的数据对接
        BeanUtils.populate(rsGcyUpdate, buffer);
        spcyRsGcyService.updateById(rsGcyUpdate);

        String operContent = "基本信息修改：";
        Map<String, Object> oldMap = ObjectToMapUtils.objectToMap(oldRsGcy);
        operContent += LogUtils.BeanModifyMsg(rsGcyUpdate,oldMap);

        spcyLogService.addLogs(LogConstant.LOGS_RS_GCY,operContent,gcyId,LogConstant.LOGS_RS_GCY,SpcyConstant.LOGS_SYS_TYPE_XG);
        return HttpResult.ok("修改成功");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @Log(title = "审评查验-观察员库-通过id删除")
    @ApiOperation(value = "审评查验-观察员库-通过id删除")
    @DeleteMapping(value = "/delete")
    public HttpResult<?> delete(@RequestParam("id") String id) {
        if (StringUtils.isEmpty(id)){
            return HttpResult.error("id参数不能为空");
        }
        SpcyRsGcy nowGcy = spcyRsGcyService.getById(id);
        if (nowGcy == null){
            return HttpResult.error("当前观察员数据不存在，请重试");
        }
        spcyRsGcyService.removeById(id);
        String operContent = "删除信息：";
        Map<String, Object> oldMap = ObjectToMapUtils.objectToMap(nowGcy);
        operContent += LogUtils.MapToStringMethod(oldMap);
        spcyLogService.addLogs(LogConstant.LOGS_RS_GCY,operContent,id,LogConstant.LOGS_RS_GCY,SpcyConstant.LOGS_SYS_TYPE_SC);
        return HttpResult.ok("删除成功");
    }

    /**
     * 通过id批量删除
     *
     * @param ids
     * @return
     */
    @Log(title = "审评查验-观察员库-批量删除")
    @ApiOperation(value = "审评查验-观察员库-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public HttpResult<?> deleteBatch(@RequestParam("ids") String ids) {
        if (StringUtils.isEmpty(ids)){
            return HttpResult.error("ids参数不能为空");
        }
        List<String> idsList = Arrays.asList(ids.split(","));
        List<SpcyRsGcy> spcyRsGcyList= spcyRsGcyService.listByIds(idsList);
        if (CollectionUtils.isEmpty(spcyRsGcyList)){
            return HttpResult.error("数据不存在，请重试");
        }
        String operContent = "";
        for (SpcyRsGcy gcy : spcyRsGcyList){
            String id = gcy.getId();
            spcyRsGcyService.removeById(id);

            operContent = "删除信息：";
            Map<String, Object> oldMap = ObjectToMapUtils.objectToMap(gcy);
            operContent += LogUtils.MapToStringMethod(oldMap);
            spcyLogService.addLogs(LogConstant.LOGS_RS_GCY,operContent,id,LogConstant.LOGS_RS_GCY,SpcyConstant.LOGS_SYS_TYPE_SC);
            operContent = "";
        }

        return HttpResult.ok("删除成功");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @Log(title = "审评查验-观察员库-通过id查询")
    @ApiOperation(value = "审评查验-观察员库-通过id查询")
    @GetMapping(value = "/queryById")
    public HttpResult<?> queryById(@RequestParam("id") String id) {
        SpcyRsGcy spcyRsGcy = spcyRsGcyService.getById(id);
        return HttpResult.ok(spcyRsGcy);
    }

    /**
     * 导入观察员数据-表格excel
     */
    @Log(title = "导入观察员数据-表格excel")
    @ApiOperation(value = "导入观察员数据-表格excel")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "file",value = "excel模板文件",required = true),
            @ApiImplicitParam(name = "fywflcode",value = "业务分类编码",required = true)
    })
    @PostMapping(value = "impRsGcyData")
    public HttpResult<?> impRsGcyData(@RequestParam("file") MultipartFile file, @RequestParam("fywflcode")String ywflCode){
        if (file.isEmpty()){
            return HttpResult.error("文件不存在");
        }

        //获取文件名
        String fileName = file.getOriginalFilename();
        //判断文件类型，这里我们只要xls文件
        if (fileName != null && !fileName.endsWith(".xls") && !fileName.endsWith(".xlsx"))
            return HttpResult.error(1, "请选择“xls”或“xlsx”文件");

        File fileUpload = localFileUploadUtils.uploadDempFile(file,fileName);
        // 获取导入的数据
        List<Map<String, Object>> mapsList = null;
        try {
            mapsList = myExcelUtils.paresExclToMapList(BusinessConstant.IMPORT_RS_GCY_XML, fileUpload);
        } catch (Exception e) {
            log.error("导入检察员数据出错-{}",e.getMessage());
        }
        if (CollectionUtils.isNotEmpty(mapsList) && mapsList.size() > 0) {
            int xh = 0;
            for (Map map : mapsList) {
                xh = xh + 1;
                spcyRsGcyService.impRsHcyData(map,ywflCode,xh);
            }
        }
        fileUpload.delete();
        return HttpResult.ok("导入成功");
    }

    /**
     * 下载观察员-导入模板
     * @param response
     */
    @Log(title = "下载观察员-导入模板")
    @ApiOperation(value = "下载观察员-导入模板")
    @GetMapping("/downRsGcyTemplate")
    public void downRsGcyTemplate(HttpServletResponse response){
        try {
            response.setContentType("application/ms-excel;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=".concat(String.valueOf(URLEncoder.encode("gcyImpTemplate.xls", "UTF-8"))));
            OutputStream out = response.getOutputStream();
            myExcelUtils.buildImpModel(BusinessConstant.IMPORT_RS_GCY_XML, out);
        } catch (Exception e) {
            log.error("下载检查员模板错误-{}",e.getMessage());
        }
    }

    /**
     * 导出观察员数据-表格excel
     */
    @Log(title = "导出观察员数据-表格excel")
    @ApiOperation(value = "导出观察员数据-表格excel")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "ids",value = "观察员字符逗号分割",dataType = "String")
    })
    @GetMapping("/exportRsGcyData")
    public void exportRsGcyData(@RequestParam(value = "ids",defaultValue = "")String ids,
                            SpcyRsGcy spcyRsGcy,
                            HttpServletResponse response){
        try {
            String name = "exportRsGcy";
            response.setContentType("application/ms-excel;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename="
                    .concat(String.valueOf(URLEncoder.encode(name+".xls", "UTF-8"))));
            OutputStream out = response.getOutputStream();

            List<String> IdsList = Arrays.asList(ids.split(","));
            List<Object> list = new ArrayList<>(); // 导出的数据
            // 多选导出
            if (StringUtils.isNotEmpty(ids)) {
                List<SpcyRsGcy> rsGcyList = spcyRsGcyService.listByIds(IdsList);
                if (CollectionUtils.isNotEmpty(rsGcyList)){
                    for (SpcyRsGcy e : rsGcyList){
                        list.add(e);
                    }
                }
            }else {
                LambdaQueryWrapper<SpcyRsGcy> queryWrapper = new LambdaQueryWrapper();
                queryWrapper.like(StringUtils.isNotEmpty(spcyRsGcy.getFdwmc()),SpcyRsGcy::getFdwmc,spcyRsGcy.getFdwmc());
                queryWrapper.like(StringUtils.isNotEmpty(spcyRsGcy.getFgcyxm()),SpcyRsGcy::getFgcyxm,spcyRsGcy.getFgcyxm());
                queryWrapper.like(StringUtils.isNotEmpty(spcyRsGcy.getFszds()),SpcyRsGcy::getFszds,spcyRsGcy.getFszds());
                queryWrapper.orderByAsc(SpcyRsGcy::getForder);
                List<SpcyRsGcy> rsGcyList = spcyRsGcyService.list(queryWrapper);
                // 条件导出
                if (CollectionUtils.isNotEmpty(rsGcyList)){
                    for (SpcyRsGcy e : rsGcyList){
                        list.add(e);
                    }
                }
            }
            myExcelUtils.outputListToExclFile(BusinessConstant.IMPORT_RS_GCY_XML,list,out); // 导出模板数据成excel
        } catch (Exception e) {
            log.error("导出观察员数据出错-{}",e.getMessage());
        }
    }

    @Log(title = "获取观察员-对应的业务类型")
    @ApiOperation(value = "获取观察员-对应的业务类型")
    @GetMapping(value = "queryGcyListByYwfl")
    public HttpResult<?> queryGcyListByYwfl(SpcyRsGcy gcy,
                                            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                            @RequestParam(name = "pageSize", defaultValue = "30") Integer pageSize){

        Page<SpcyRsGcy> page = new Page<>(pageNo,pageSize);
        LambdaQueryWrapper<SpcyRsGcy> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(gcy.getFgcyxm()),SpcyRsGcy::getFgcyxm,gcy.getFgcyxm());
        queryWrapper.like(StringUtils.isNotBlank(gcy.getFdwmc()),SpcyRsGcy::getFdwmc,gcy.getFdwmc());
        queryWrapper.like(StringUtils.isNotBlank(gcy.getFszds()),SpcyRsGcy::getFszds,gcy.getFszds());
        queryWrapper.like(StringUtils.isNotBlank(gcy.getFemail()),SpcyRsGcy::getFemail,gcy.getFemail());
        queryWrapper.like(StringUtils.isNotBlank(gcy.getFphone()),SpcyRsGcy::getFphone,gcy.getFphone());
        queryWrapper.orderByAsc(SpcyRsGcy::getForder);
        queryWrapper.orderByAsc(SpcyRsGcy::getCreateTime);

        // 对应业务的观察员
        IPage<SpcyRsGcy> rsGcyList = spcyRsGcyService.page(page,queryWrapper);

        return HttpResult.ok(rsGcyList);
    }

    @Log(title = "查询所有观察员(监管部门)")
    @ApiOperation(value = "查询所有观察员(监管部门)")
    @GetMapping(value = "queryAllJgbm")
    public HttpResult queryAllJgbm(SpcyRsGcy gcy){
        LambdaQueryWrapper<SpcyRsGcy> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(gcy.getFgcyxm()),SpcyRsGcy::getFgcyxm,gcy.getFgcyxm());
        queryWrapper.like(StringUtils.isNotBlank(gcy.getFdwmc()),SpcyRsGcy::getFdwmc,gcy.getFdwmc());
        queryWrapper.like(StringUtils.isNotBlank(gcy.getFszds()),SpcyRsGcy::getFszds,gcy.getFszds());
        queryWrapper.like(StringUtils.isNotBlank(gcy.getFemail()),SpcyRsGcy::getFemail,gcy.getFemail());
        queryWrapper.like(StringUtils.isNotBlank(gcy.getFphone()),SpcyRsGcy::getFphone,gcy.getFphone());
        queryWrapper.orderByAsc(SpcyRsGcy::getForder);
        queryWrapper.orderByAsc(SpcyRsGcy::getCreateTime);

        List<SpcyRsGcy> list = spcyRsGcyService.list(queryWrapper);

        Map resultMap = new HashMap();
        resultMap.put("records", list);
        return HttpResult.ok(resultMap);
    }

    @Log(title = "保存选中的观察员-通过申请事项")
    @ApiOperation(value = "保存选中的观察员-通过申请事项")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "sqsxid",value = "申请事项id",required = true),
            @ApiImplicitParam(name = "id",value = "观察员id",required = true)
    })
    @PostMapping(value = "saveSelectedGcyToSqsx")
    public HttpResult<?> saveSelectedGcyToSqsx(@RequestBody Map<String,String> map){
        String sqsxid = map.get("sqsxid");
        String id = map.get("id");

        if (StringUtils.isBlank(sqsxid)){
            return HttpResult.error("申请事项参数不存在，请联系管理员");
        }
        if (StringUtils.isBlank(id)){
            return HttpResult.error("请选择观察员");
        }
        SpcySqsxBasic sqsx = spcySqsxBaiscService.getById(sqsxid);
        if (sqsx == null){
            return HttpResult.error("当前申请事项不存在，请刷新重试");
        }
        SpcyRsGcy gcy = spcyRsGcyService.getById(id);
        if (gcy == null){
            return HttpResult.error("当前观察员不存在，请刷新重试");
        }
        sqsx.setFcygcyid(gcy.getId());
        sqsx.setFcygcy(gcy.getFgcyxm());
        sqsx.setFcygcybm(gcy.getFdwmc());
        spcySqsxBaiscService.updateById(sqsx);


        String logNr = "初始化观察员：【观察员id】设置为["+gcy.getId()+"];" +
                "【观察员姓名】设置为["+gcy.getFgcyxm()+"];【观察员部门】设置为["+gcy.getFgcyxm()+"]";
        spcyLogService.addLogs("方案制作",logNr,sqsxid,LogConstant.LOGS_SQSX_BASIC,SpcyConstant.LOGS_SYS_TYPE_BC);

        return HttpResult.ok("选择成功");
    }

}
